<template>
  <div class="register-form">
    <h2 class="register-title">用户注册</h2>
    <el-form :model="registerForm" ref="registerFormRef" :rules="rules">
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入用户名"
          prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请确认密码"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="code">
        <div class="captcha-container">
          <el-input
            v-model="registerForm.code"
            placeholder="请输入验证码"
            prefix-icon="Key"
          />
          <img 
            :src="captchaUrl" 
            @click="refreshCaptcha" 
            alt="验证码"
            class="captcha-img"
          >
        </div>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary" 
          class="register-button" 
          :loading="loading"
          @click="handleSubmit"
        >
          {{ loading ? '注册中...' : '注册' }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="login-section">
      <span class="login-text">已有账号？</span>
      <el-button 
        type="text" 
        class="login-link"
        @click="handleBackToLogin"
      >
        返回登录
      </el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'

export default defineComponent({
  name: 'RegisterModal',
  emits: ['switch-to-login', 'register-success'],
  setup(props, { emit }) {
    const loading = ref(false)
    const registerFormRef = ref<FormInstance>()
    
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      code: '',
      uuid: ''
    })

    const validatePass2 = (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = reactive<FormRules>({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    })

    const captchaUrl = ref('')

    const getCaptcha = async () => {
      try {
        const res = await request.get('/captchaImage')
        if (res.code === 200) {
          captchaUrl.value = 'data:image/gif;base64,' + res.img
          registerForm.uuid = res.uuid
        }
      } catch (error) {
        console.error('获取验证码失败:', error)
      }
    }

    const refreshCaptcha = () => {
      getCaptcha()
    }

    const handleSubmit = async () => {
      if (!registerFormRef.value) return
      
      await registerFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const { confirmPassword, ...submitForm } = registerForm
            const res = await request.post('/register', submitForm)
            if (res.code === 200) {
              ElMessage.success('注册成功')
              emit('register-success')
              emit('switch-to-login')
            }
          } catch (error) {
            console.error('注册失败:', error)
            refreshCaptcha()
          } finally {
            loading.value = false
          }
        }
      })
    }

    const handleBackToLogin = () => {
      emit('switch-to-login')
    }

    onMounted(() => {
      getCaptcha()
    })

    return {
      registerForm,
      registerFormRef,
      rules,
      loading,
      captchaUrl,
      handleSubmit,
      refreshCaptcha,
      handleBackToLogin
    }
  }
})
</script>

<style scoped>
.register-form {
  padding: 30px;
}

.register-title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-img {
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
}

.register-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.login-section {
  text-align: center;
  margin-top: 16px;
  color: #666;
}

.login-text {
  font-size: 14px;
  margin-right: 4px;
}

.login-link {
  font-size: 14px;
  padding: 0 4px;
}

:deep(.login-link.el-button) {
  font-weight: 600;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
}
</style> 